<template>
  <div class="base-content">
    <div class="basic-info">
      <!--操作栏-->
      <div class="base-content-operate">
        <el-button
          v-rights="'Add'"
          icon="el-icon-plus"
          type="primary"
          @click="addEntrustOrder"
          >新增</el-button
        >
        <el-button
          v-rights="'Copy'"
          :disabled="submitLoadCopy"
          icon="el-icon-document-copy"
          type="primary"
          @click="copyEntrustOrder"
          >复制</el-button
        >
        <el-button
          v-rights="'Import'"
          icon="el-icon-document-copy"
          type="primary"
          @click="importData()"
          >导入</el-button
        >
        <el-button
          v-rights="'Export'"
          v-loading="submitLoadExport"
          icon="el-icon-document-copy"
          type="primary"
          @click="exportData()"
          >导出</el-button
        >
        <el-button
          v-rights="'Delete'"
          :disabled="!submitLoad"
          icon="el-icon-delete"
          type="danger"
          @click="deleteEntrustOrder"
          >删除</el-button
        >
      </div>
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="已提交" name="first"></el-tab-pane>
        <el-tab-pane label="草稿" name="second"></el-tab-pane>
      </el-tabs>
      <!--列表-->
      <el-table
        ref="table"
        v-loading="tableLoad"
        class="filter unsetborder"
        :class="{ 'show-filter': showFilterRow }"
        :data="tableData"
        height="calc(100% - 190px)"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55">
          <el-table-column type="selection"></el-table-column>
        </el-table-column>
        <el-table-column align="center" width="50">
          <template #header>
            <div class="filter-icon" title="筛选">
              <SvgIcon
                class-name="filter"
                icon-class="filter"
                @click="filterIconClick"
              />
            </div>
          </template>
          <el-table-column width="50"></el-table-column>
        </el-table-column>

        <el-table-column label="委托单号">
          <el-table-column prop="orderNum">
            <template #header>
              <el-input
                v-if="showFilterRow"
                v-model="filterForm.orderNum"
                @keyup.enter.native="onQuery"
              ></el-input>
            </template>
          </el-table-column>
        </el-table-column>
        <el-table-column label="委托单位">
          <el-table-column prop="customerName">
            <template #header>
              <el-input
                v-if="showFilterRow"
                v-model="filterForm.customerName"
                @keyup.enter.native="onQuery"
              ></el-input>
            </template>
          </el-table-column>
        </el-table-column>
        <el-table-column label="委托人">
          <el-table-column prop="entrustPeople">
            <template #header>
              <el-input
                v-if="showFilterRow"
                v-model="filterForm.entrustPeople"
                @keyup.enter.native="onQuery"
              ></el-input>
            </template>
          </el-table-column>
        </el-table-column>
        <el-table-column label="样品名称">
          <el-table-column prop="sampleName">
            <template #header>
              <el-input
                v-if="showFilterRow"
                v-model="filterForm.sampleName"
                @keyup.enter.native="onQuery"
              ></el-input>
            </template>
          </el-table-column>
        </el-table-column>
        <el-table-column label="状态">
          <el-table-column prop="entrustOrderStatusName">
            <template #header>
              <el-select
                ref="select"
                v-model="filterForm.orderStatusCode"
                placeholder="请选择"
              >
                <el-option
                  v-for="item in dicOrderStatusList"
                  :key="item.value"
                  :label="item.name"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </template>
            <template slot-scope="scope">
              <el-link
                v-if="
                  scope.row.orderStatusCode == 20 ||
                  scope.row.orderStatusCode == 40
                "
                type="primary"
                @click="orderStatusCodeClick(scope.row)"
                >{{ scope.row.entrustOrderStatusName }}</el-link
              >
              <span v-else>
                {{ scope.row.entrustOrderStatusName }}
              </span>
            </template>
          </el-table-column>
        </el-table-column>
        <el-table-column label="核算状态">
          <el-table-column prop="entrustOrderPriceStatusName">
            <template #header>
              <el-select
                ref="select"
                v-model="filterForm.orderPriceStatusCode"
                placeholder="请选择"
              >
                <el-option
                  v-for="item in dicOrderPriceStatusList"
                  :key="item.value"
                  :label="item.name"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </template>
          </el-table-column>
        </el-table-column>
        <el-table-column label="提交时间">
          <el-table-column prop="createTime">
            <template #header>
              <el-date-picker
                v-model="filterForm.createTimeArr"
                type="datetimerange"
                :picker-options="pickerOptions"
                value-format="yyyy-MM-dd HH:mm"
                format="yyyy-MM-dd HH:mm"
                align="right"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :default-time="['00:00:00', '00:00:00']"
              ></el-date-picker>
            </template>
          </el-table-column>
        </el-table-column>
        <el-table-column label="报告领取时间">
          <el-table-column prop="reportGetDateTime">
            <template #header>
              <el-date-picker
                v-model="filterForm.reportGetDateTimeArr"
                type="datetimerange"
                :picker-options="pickerOptions"
                value-format="yyyy-MM-dd HH:mm"
                format="yyyy-MM-dd HH:mm"
                align="right"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :default-time="['00:00:00', '00:00:00']"
              ></el-date-picker>
            </template>
          </el-table-column>
        </el-table-column>
        <el-table-column label="操作">
          <el-table-column width="140">
            <template #header>
              <div v-if="showFilterRow" class="search-operate">
                <el-link type="primary" @click="onQuery">搜索</el-link>
                <el-link @click="cancelForm">清空</el-link>
              </div>
            </template>
            <template slot-scope="scope">
              <div class="base-table-operation">
                <el-link
                  v-if="activeName == 'second'"
                  v-rights="'Edit'"
                  type="primary"
                  @click="editUnit(scope.row)"
                  >编辑</el-link
                >
                <el-link
                  v-rights="'Query'"
                  type="primary"
                  @click="selUnit(scope.row)"
                  >查看</el-link
                >
                <el-link
                  v-rights="'FileGetList'"
                  type="primary"
                  @click="selFile(scope.row)"
                  >附件</el-link
                >
                <el-link
                  v-if="activeName == 'first'"
                  v-rights="'Chehui'"
                  :disabled="!submitLoad"
                  type="primary"
                  @click="chehui(scope.row)"
                  >撤回</el-link
                >
              </div>
            </template>
          </el-table-column>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <BasePagination
        :total="pagination.total"
        :page-index="pagination.pageIndex"
        :page-size="pagination.pageSize"
        @sizeChange="sizeChange"
        @changePage="currentChange"
      />
    </div>
    <AccessoryDialog
      v-if="accrssoryVisible"
      :accrssory-visible.sync="accrssoryVisible"
      :entrust-order-id.sync="entrustOrderId"
    />
    <EntrustOrderDialog
      v-if="dialogFormVisible"
      ref="EntrustOrderDialog"
      :dialog-form-visible.sync="dialogFormVisible"
      :read-only.sync="readOnly"
      :edit-id.sync="editId"
      @closeDialog="closeDialog"
    />
    <ImportComponents
      ref="ImportComponents"
      v-model="importVisible"
      @success="closeDialog"
      @UploadMethod="UploadMethod"
      @DownloadMethod="DownloadMethod"
    />
  </div>
</template>
<script>
import {getDictList} from "@/ModuleSystem/api/System/SystemDict.js";
import {
  getEntrustOrderList,
  Copy,
  Delete,
  Chehui,
} from "../../../api/EntrustManage/EntrustOrder.js";
import {
  ExportWord,
  DownloadExportWordZip,
} from "../../../api/EntrustManage/ExportWord.js";
import { CommonConstStatus } from "../../../utils/dictionary.js";
import EntrustOrderDialog from "./EntrustOrderDialog.vue";
import AccessoryDialog from "./AccessoryDialog.vue";
import _ from "lodash";
import {
  ImportEntrustUrl,
  DownloadEntrustOrderTemplate,
} from "../../../api/EntrustManage/EntrustOrder.js";
import { GetStaticFileInfo } from "@/api/Base";
export default {
  name: "EntrustOrderList",
  components: { EntrustOrderDialog, AccessoryDialog },
  data() {
    return {
      pickerOptions: {
        selectableRange: "00:00:00 - 23:59:59",
        disabledDate(date) {
          return date.getTime() > Date.now();
        },
      },
      dicOrderStatusList: [],
      dicOrderPriceStatusList: [],
      showFilterRow: false,
      submitLoadExport: false,
      submitLoadCopy: false,
      count: 0,
      submitLoad: true,
      accrssoryVisible: false,
      importVisible: false,
      drawer: false,
      direction: "rtl",
      titleDrawer: "",
      dialogFormVisible: false,
      searchLoading: false,
      loading: false,
      isShowDialog: false,
      editId: "",
      entrustOrderId: "",
      CommonConstStatus,
      filterForm: {
        orderNum: "",
        customerName: "",
        entrustPeople: "",
        sampleName: "",
        createTimeArr: [],
        reportGetDateTimeArr: [],
        startCreateTime: "",
        endCreateTime: "",
        startReportGetDateTime: "",
        endReportGetDateTime: "",
        entrustOrderState: 1,
        orderStatusCode: "-1",
        orderPriceStatusCode: "-1",
      },
      pagination: {
        pageIndex: 1,
        pageSize: 10,
        total: 0,
      },
      tableLoad: false,
      tableData: [],
      tableDatas: [],
      readOnly: false,
      activeName: "first",
      systemType: "",
    };
  },
  computed: {},
  created() {
    getDictList({ dictCode: "OrderStatus" })
      .then((res) => {
        this.dicOrderStatusList = res.data;

        this.dicOrderStatusList = this.dicOrderStatusList.filter((item) => {
          return "草稿".indexOf(item.name) < 0;
        });

        var obj = {};
        obj.id = "-1";
        obj.value = "-1";
        obj.name = "全部";
        this.dicOrderStatusList.unshift(obj);
      });

    getDictList({ dictCode: "EntrustPricelStatus" })
      .then((res) => {
        this.dicOrderPriceStatusList = res.data;
        var obj = {};
        obj.id = "-1";
        obj.value = "-1";
        obj.name = "全部";
        this.dicOrderPriceStatusList.unshift(obj);
      });

    this.getList();
  },
  methods: {
    orderStatusCodeClick(row) {
      if (Number(row.orderStatusCode) === 20) {
        this.$router.push({
          path: "/SampleRegistrationList",
          query: { entrustOrderId: row.id },
        });
      } else if (Number(row.orderStatusCode) === 40) {
        this.$router.push({
          path: "/ReportStandingBookList",
          query: { entrustOrderId: row.id },
        });
      }
    },

    onQuery() {
      this.pagination.pageIndex = 1;
      this.getList("filter");
    },

    filterIconClick() {
      this.showFilterRow = !this.showFilterRow;
      !this.showFilterRow && this.cancelForm();
    },
    // 下载
    DownloadMethod() {
      DownloadEntrustOrderTemplate().then((res) => {
        if (res.code === 200) {
          GetStaticFileInfo(res.data);
          // const link = document.createElement("a");
          // link.style.display = "none"; // 去除a标签的样式
          // // 设置连接
          // link.href = `${this.$baseProtocol}//${res.data}`;
          // document.body.appendChild(link);
          // 模拟点击事件;
          // link.click();
        } else {
          this.$message.error("未找到模板,请联系管理员");
        }
      });
    },
    // 上传
    UploadMethod(formData, fileCount) {
      ImportEntrustUrl(formData).then((res) => {
        if (res.code === 200) {
          this.count = this.count + 1;
          if (this.count === fileCount) {
            // 调用上传成功方法
            this.$refs.ImportComponents.successfulOperation();
          }
        } else {
          this.count = 0;
          this.$message.error(res.msg);
        }
      });
    },

    // 查看附件
    selFile(row) {
      this.entrustOrderId = row.id;
      this.accrssoryVisible = true;
    },
    // 撤回
    chehui: _.throttle(function(row) {
      if (this.submitLoad) {
        this.submitLoad = false;
        var idList = [];
        idList.push(row.id);
        Chehui({ id: idList })
          .then((res) => {
            this.submitLoad = true;
            this.$message.success("撤回成功，请前往草稿页面查看。");
            this.getList();
          })
          .catch((res) => {
            this.submitLoad = true;
            this.getList();
          });
      }
    }, 2000),
    // 点击委托单号
    orerNumClick(row) {
      this.titleDrawer = "委托单号" + row.orderNum;
      this.drawer = true;
    },
    handleClose() {
      this.drawer = false;
    },
    // 选择标签
    handleClick() {
      this.filterForm = this.$options.data().filterForm;
      this.showFilterRow = false;
      if (this.activeName === "first") {
        this.filterForm.entrustOrderState = 1;
      } else if (this.activeName === "second") {
        this.filterForm.entrustOrderState = 2;
      }
      this.getList("filter");
    },
    // 导出
    exportData() {
      var idList = [];
      if (this.tableDatas === null || this.tableDatas.length === 0) {
        this.$message.error("请选择数据");
        return false;
      }

      for (let i = 0; i < this.tableDatas.length; i++) {
        idList.push(this.tableDatas[i].id);
      }
      this.submitLoadExport = true;
      ExportWord({ id: idList, exportWordTypeEnum: 1 })
        .then((res) => {
          DownloadExportWordZip({ path: res.data, exportWordTypeEnum: 1 })
            .then((res) => {
              this.submitLoadExport = false;
              var blob = new Blob([res.data], {
                type: "application/octet-stream",
              });
              var url = window.URL.createObjectURL(blob);
              const link = document.createElement("a"); // 创建a标签
              link.href = url;
              link.download = "委托单.zip"; // 重命名文件
              link.click();
              URL.revokeObjectURL(url); // 释放内存
            })
            .catch(() => {
              this.submitLoadExport = false;
            });
        })
        .catch(() => {
          this.submitLoadExport = false;
        });
    },
    // 导入
    importData() {
      this.importVisible = true;
    },
    handleSelectionChange(val) {
      this.tableDatas = val;
    },
    // 删除
    deleteEntrustOrder: _.throttle(function() {
      if (
        this.tableDatas === undefined ||
        this.tableDatas === null ||
        this.tableDatas.length === 0
      ) {
        this.$message.error("请选择数据");
        return false;
      }

      if (this.submitLoad) {
        this.submitLoad = false;
        var idList = [];
        for (let i = 0; i < this.tableDatas.length; i++) {
          idList.push(this.tableDatas[i].id);
        }
        this.$confirm("是否确定删除此委托单?", "删除委托单", {
          type: "warning",
          confirmButtonText: "确定",
          okType: "danger",
          center: true,
          cancelButtonText: "取消",
          beforeClose: (action, instance, done) => {
            if (action === "confirm") {
              Delete({ id: idList })
                .then((res) => {
                  this.submitLoad = true;
                  done();
                  this.getList();
                })
                .catch(() => {
                  this.submitLoad = true;
                });
            } else {
              this.submitLoad = true;
              done();
            }
          },
        }).catch(() => {
          this.submitLoad = true;
        });
      }
    }, 2000),
    // 复制
    copyEntrustOrder: _.throttle(function() {
      if (this.tableDatas === null || this.tableDatas.length === 0) {
        this.$message.error("请选择数据");
        return false;
      }
      this.submitLoadCopy = true;
      var data = { id: [] };
      for (let i = 0; i < this.tableDatas.length; i++) {
        data.id.push(this.tableDatas[i].id);
      }
      Copy(data)
        .then((res) => {
          this.submitLoadCopy = false;
          this.getList();
        })
        .catch(() => {
          this.submitLoadCopy = false;
        });
    }, 3000),
    // 修改
    editUnit(row) {
      this.editId = row.id;
      this.dialogFormVisible = true;
    },
    // 查看
    selUnit(row) {
      this.readOnly = true;
      this.editId = row.id;
      this.dialogFormVisible = true;
    },
    addEntrustOrder() {
      this.dialogFormVisible = true;
    },
    getList(flag) {
      if (flag) {
        this.pagination.pageIndex = 1;
      }
      this.loading = true;
      getEntrustOrderList({ ...this.filterForm, ...this.pagination })
        .then((res) => {
          console.log(res);
          this.tableData = res.data ? res.data.dataList : [];
          this.pagination.total = res.data ? res.data.total : 0;
          this.loading = false;
        })
        .catch(() => {
          this.loading = false;
        });
    },
    // 清空筛选条件
    cancelForm() {
      this.filterForm = this.$options.data().filterForm;
      this.getList("filter");
    },
    // 关闭弹框清空id
    closeDialog() {
      this.editId = "";
      this.readOnly = false;
      this.getList();
    },
    // 切换页码
    sizeChange(val) {
      this.pagination.pageIndex = 1;
      this.pagination.pageSize = val;
      this.getList();
    },
    currentChange(val) {
      this.pagination.pageIndex = val;
      this.getList();
    },
  },
};
</script>
